package book.demo;

/**
 * 测试：并发一定比串行快吗？
 * 当count < 10000时，串行更快，因为线程创建和启动需要大量时间
 */
public class ConcurrencyTest {

    private static final long count = 10000L;

    public static void main(String[] args) throws InterruptedException {
        concurrency();
        serial();
    }

    public static void concurrency() throws InterruptedException {
        long start = System.nanoTime();
        Thread t = new Thread() {
            @Override
            public void run() {
                int a = 0;
                for (int i = 0; i < count; i++) {
                    a += 5;
                }
            }
        };
        t.start();

        int b = 0;
        for (int i = 0; i < count; i++) {
            b--;
        }

        t.join();
        long time = System.nanoTime() - start;
        System.out.println("concurrency expend time：" + time);
    }

    public static void serial() {
        long start = System.nanoTime();

        int a = 0;
        for (int i = 0; i < count; i++) {
            a += 5;
        }

        int b = 0;
        for (int i = 0; i < count; i++) {
            b--;
        }

        long time = System.nanoTime() - start;
        System.out.println("serial expend time：" + time);
    }
}
